<?php

namespace App\Services;

use App\AccessLog;
use App\AppChannel;
use App\AppWhiteList;
use App\BlackAccessLog;
use App\ReferBlackUrl;
use App\ReferLog;
use App\ReferSmsLog;
use App\UserApp;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Redis;
use Jenssegers\Agent\Agent;

/**
 * Class ApiService
 *
 * @package \App\Services
 */
class ApiService extends BaseService
{
    private $useAgent = "";
    private $header = "";
    private $cookie = "";
    private $refer = "";

    /**
     * ApiService constructor.
     *
     * @param array $header
     */
    public function __construct(array $header)
    {
        $useAgent = $header["useAgent"];
        $cookie = $header["cookie"];
        $refer = $header["refer"];
        $this->useAgent = $useAgent;
        $this->header = $header;
        $this->cookie = $cookie;
        $this->refer = $refer;
    }


    /**
     * 处理逻辑
     *
     * @param string $keyword
     * @param string $ip
     * @return array
     */
    public function doParse($keyword, $ip = '')
    {
        $result = [];
        $channelResult = AppChannel::where("short_url_word", $keyword)->first();

        if (!empty($channelResult)) {

            // 判断APP是否已删除 删除直接返回404
            $appRes = UserApp::where("id", $channelResult->app_id)->first();

            if (empty($appRes) || $appRes->del_flag == 1) {
                return abort(404);
            }

//            $result["iframeUrl"] = $channelResult->register_url;
//            if (empty($channelResult->share_flag)) {
//                $result["newUrl"] = route("url/index2", ["keyword" => $keyword]) . "?source=nof";//rand(100, 999)
//            } else {
//                $result["newUrl"] = route("url/index2", ["keyword" => $keyword]);
//            }



            // 收集访问日志
            $cookieValue = isset($this->cookie['guid']) ? $this->cookie['guid'] : '';
            $visitorUrl = "";
            AccessLog::insert(["channel_id" => $channelResult->id, "app_id" => $channelResult->app_id,
                "cookie_value" => $cookieValue, "vistor_url" => $visitorUrl, "visitor_ip" => $ip,
                "refer_value" => $this->refer,
                "access_date" => date("Y-m-d"), "created_at" => date("Y-m-d H:i:s")
            ]);

            $isMingZhong = $this->addBlackAccessLog($channelResult, $this->refer, $ip);

            if (!empty($isMingZhong)) {
                if (!empty($isMingZhong->source_type) && $isMingZhong->source_type == 'weixin') {
                    $result["newUrl"] = route("url/index2", ["keyword" => $keyword]) . "?source=mof";
                }

                $forwardUrl = UserApp::where("id", $channelResult->app_id)->value("redirect_url");
                $result["iframeUrl"] = $forwardUrl;
            } else {
                setcookie("refresh_i", 20191117, time() + 300);
            }


            // 兼容iphone下载
            if ($channelResult->app_id) {
                // agent 判断
                $agent = new Agent();
                $userAgent = strtolower($agent->getUserAgent());
                if (in_array($channelResult->app_id, ["297", "281"])) {
                    if (in_array($channelResult->id, ["1306", "1307", "1285", "1284", "1242",  "1395", "1408", "1396", "1397", "1425", "1083", "1424"])) {
                        if (!empty($isMingZhong)) {
                            //header('HTTP/1.1 301 Moved Permanently');
                            header('Plateform: mtop');

                            header('location:' . $forwardUrl);
                            exit;
                        }
                        //header('HTTP/1.1 301 Moved Permanently');
                        header('Plateform: mtop');

                        header('location:' . $channelResult->register_url);
                        exit;
                    }
                }

                if ($channelResult->app_id == 280 || $channelResult->app_id == 284) {

                    if (!empty($isMingZhong)) {
                        //header('HTTP/1.1 301 Moved Permanently');
                        header('Plateform: mtop');
                        header('location:' . $forwardUrl);
                        exit;
                    }
                    if (strpos($userAgent, 'android') !== false) {
                        //header('HTTP/1.1 301 Moved Permanently');
                        header('Plateform: mtop');

                        header('location:' . $channelResult->register_url);
                        exit;

                    }
                    //header('location:' . $channelResult->register_url);
                }


                if ($appRes->redirect_switch == 1) {
                    if (strpos($userAgent, 'iphone') !== false) {
                        if (!empty($isMingZhong)) {
                            //header('HTTP/1.1 301 Moved Permanently');
                            header('Plateform: mtop');

                            header('location:' . $forwardUrl);
                            exit;
                        }
                        //header('HTTP/1.1 301 Moved Permanently');
                        header('Plateform: mtop');

                        header('location:' . $channelResult->register_url);
                        exit;

                    }
                }
            }
        }
        return $result;
    }


    /**
     * 添加黑名单访问日志
     *
     * @param        $channelResult
     * @param string $referer
     * @param string $ip
     * @return mixed
     */
    public function addBlackAccessLog($channelResult, $referer = '', $ip = '')
    {
        $insertParam = [
            "app_id" => $channelResult->app_id,
            "channel_id" => $channelResult->id,
            "from_url" => $referer,
            "access_date" => date("Y-m-d"),
            "visitor_ip" => $ip
        ];

        // refer处理
        if (!empty($referer)) {

            $appName = UserApp::where("id", $channelResult->app_id)->value("name");
            // refer 收集日志
            ReferLog::create(["url" => $referer, "type" => 1,"channel_id" => $channelResult->id,
                "channel_name" => $channelResult->name, "app_id" => $channelResult->app_id,
                "app_name" => $appName
            ]);


            $host = $this->getHost($referer);

            if (!empty($host)) {
                //$host = str_replace(["http://", "https://", "www."], ["", ""], $host);
                $host = strtolower($host);
                $host = str_replace("www.", "", $host);
                $host = str_replace(".com.cn", ".com", $host);

                $hostArr = explode(".", $host);
                if (count($hostArr) == 3) {
                    $host = $hostArr[1] . "." . $hostArr[2];
                }

                // 只处理安卓
                if ($this->isAndorid()) {
                    // 优先处理白名单
                    $whiteUrls = AppWhiteList::where("channel_id", $channelResult->id)->pluck('item_value');

                    if (collect($whiteUrls)->isNotEmpty()) {
                        $flag = false;

                        if (strpos($host, "lhxq.top") == false) {
                            foreach ($whiteUrls as $whiteUrl) {
                                if (strpos($whiteUrl, $host) !== false) {
                                    $flag = true;
                                    \Log::info($channelResult->name . " 白名单命中 refer 了 【" . $host . "】");

                                    break;
                                }
                            }

                            if (!$flag) {
                                $insertParam["source_type"] = "white";
                                $insertParam["from_url"] = $host;

                                return BlackAccessLog::create($insertParam);
                            } else {
                                \Log::info($channelResult->name . " 白名单 refer 通过了....");

                                return [];
                            }
                        } else {
                            return [];
                        }
                    }
                }


                $referResult = ReferBlackUrl::where(["type" => 1, "status" => 1,"del_flag" => 0])->where("url",  "like", "%" . $host ."%")->first();
                if (!empty($referResult)) {
                    // 获取手机号是都填写
                    $mobile = UserApp::where("id", $channelResult->app_id)->value("mobile");
                    if (!empty($mobile)) {
                        // 发送短信提醒
                        $smsRes = ReferSmsLog::where(["refer_id" => $referResult->id, "channel_id" => $channelResult->id])->first();

                        if (empty($smsRes)) {
                            $insertSmsParam = [
                                "app_id" => $channelResult->app_id,
                                "channel_id" => $channelResult->id,
                                "refer_id" => $referResult->id,
                                "sms_code" => "SMS_177257187",
                                "created_at" => date("Y-m-d H:i:s"),
                                "updated_at" => date("Y-m-d H:i:s")
                            ];
                            $service = new AliSmsService();
                            $service->sendNotifySms($mobile, $channelResult->name);
                            ReferSmsLog::insert($insertSmsParam);
                        }
                    }

                    $insertParam["source_type"] = "refer";
                    $insertParam["black_refer_id"] = $referResult->id;


                    return BlackAccessLog::create($insertParam);
                }
            }
        }

        // 获取头部信息
        $header = request()->header("X-Requested-With", '');

        if (!empty($header)) {

            $header = strtolower($header);

            $appName = UserApp::where("id", $channelResult->app_id)->value("name");
            // 记录日志
            ReferLog::create(["url" => $header, "type" => 2,"channel_id" => $channelResult->id,
                "channel_name" => $channelResult->name, "app_id" => $channelResult->app_id,
                "app_name" => $appName
            ]);


            // 只处理安卓
            if ($this->isAndorid()) {
                // 优先处理白名单
                $whiteUrls2 = AppWhiteList::where("channel_id", $channelResult->id)->pluck('item_value');
                if (collect($whiteUrls2)->isNotEmpty()) {
                    $flag = false;
                    foreach ($whiteUrls2 as $whiteUrl2) {
                        if (strpos($whiteUrl2, $header) !== false) {
                            $flag = true;
                            \Log::info($channelResult->name .  " 白名单命中 包 了 【" . $header . "】");
                            break;
                        }
                    }

                    if (!$flag) {
                        $insertParam["source_type"] = "white";
                        $insertParam["from_url"] = $header;
                        return BlackAccessLog::create($insertParam);
                    } else {
                        \Log::info($channelResult->name .  " 白名单 包 通过了....");
                        return [];
                    }
                }

                if ($channelResult->app_id == 301) {
                    \Log::info($header);
                    if ($header == "com.ggfqggfq.best") {
                        header('Location: ' . $channelResult->register_url);
                        exit;
                    }
                }
            }

            $blackAgentList0 = ReferBlackUrl::where(["type" => 2, 'status' => 1,"del_flag" => 0])->get(["id", "url"]);
            if (!$blackAgentList0->isEmpty()) {
                foreach ($blackAgentList0 as $vv) {
                    if (strpos(strtolower($vv->url), $header) !== false) {
                        $insertParam["source_type"] = "refer";
                        $insertParam["black_refer_id"] = $vv->id;


                        // 获取手机号是都填写
                        $mobile = UserApp::where("id", $channelResult->app_id)->value("mobile");
                        if (!empty($mobile)) {
                            // 发送短信提醒
                            $smsRes = ReferSmsLog::where(["refer_id" => $vv->id, "channel_id" => $channelResult->id])->first();

                            if (empty($smsRes)) {
                                $insertSmsParam = [
                                    "app_id" => $channelResult->app_id,
                                    "channel_id" => $channelResult->id,
                                    "refer_id" => $vv->id,
                                    "sms_code" => "SMS_177257187",
                                    "created_at" => date("Y-m-d H:i:s"),
                                    "updated_at" => date("Y-m-d H:i:s")
                                ];
                                $service = new AliSmsService();
                                $service->sendNotifySms($mobile, $channelResult->name);
                                ReferSmsLog::insert($insertSmsParam);
                            }
                        }

                        return BlackAccessLog::create($insertParam);
                    }
                }
            }
        }


        // agent 判断
        $agent = new Agent();
        $userAgent = $this->useAgent;
        if ($this->isAndorid()) {
            // 优先处理白名单
            $whiteUrls3 = AppWhiteList::where("channel_id", $channelResult->id)->pluck('item_value');

            if (collect($whiteUrls3)->isNotEmpty()) {
                $insertParam["source_type"] = "white";
                if (strpos($userAgent, "qq/") !== false || strpos($userAgent, "micromessenger") !== false) {
                    $insertParam["from_url"] = "微信/QQ";
                } else {
                    $insertParam["from_url"] = "非微信/QQ";
                }
                return BlackAccessLog::create($insertParam);
            }
        }

        $deviceType = $this->isAndoridOrIphone($userAgent);

        // 微信 QQ
        // 判断是不是微信或者手机访问 如果是的话 就忽略浏览器
        if (strpos($userAgent, "qq/") !== false || strpos($userAgent, "micromessenger") !== false) {
            if ($channelResult->weixin_flag == 0) {
                $insertParam["source_type"] = "weixin";
                return BlackAccessLog::create($insertParam);
            }
        } else {
            // 浏览器控制
            if ($channelResult->brown_flag == 0) {
                if ($agent->isTablet($userAgent)) {
                    $insertParam["source_type"] = "browser";
                    $insertParam["source_device_type"] = "pingban";
                    return BlackAccessLog::create($insertParam);
                }
                if ($agent->isDesktop($userAgent)) {
                    $insertParam["source_type"] = "browser";
                    $insertParam["source_device_type"] = "pc";
                    return BlackAccessLog::create($insertParam);
                }

                if (!empty($deviceType)) {
                    // uc 头部 安卓和苹果没啥区别
                    if (strpos($userAgent, "ucbrowser") !== false ||
                        strpos($userAgent, "ucweb") !== false
                    ) {
                        $insertParam["source_type"] = "browser";
                        $insertParam["from_url"] = "ucbrowser";
                        $insertParam["source_device_type"] = $deviceType;
                        return BlackAccessLog::create($insertParam);
                    }

                    // 百度App 安卓和苹果没啥区别
                    if (strpos($userAgent, "baiduboxapp") !== false) {
                        $insertParam["source_type"] = "browser";
                        $insertParam["from_url"] = "baiduboxapp";
                        $insertParam["source_device_type"] = $deviceType;
                        return BlackAccessLog::create($insertParam);
                    }

                    // qq浏览器
                    if (strpos($userAgent, "mqqbrowser") !== false) {
                        $insertParam["source_type"] = "browser";
                        $insertParam["from_url"] = "mqqbrowser";
                        $insertParam["source_device_type"] = $deviceType;
                        return BlackAccessLog::create($insertParam);
                    }

                    // 百度浏览器
                    if (strpos($userAgent, "baidubrowser") !== false) {
                        $insertParam["source_type"] = "browser";
                        $insertParam["from_url"] = "baidubrowser";
                        $insertParam["source_device_type"] = $deviceType;
                        return BlackAccessLog::create($insertParam);
                    }

                    // 搜狗浏览器
                    if (strpos($userAgent, "sogoumobilebrowser") !== false) {
                        $insertParam["source_type"] = "browser";
                        $insertParam["from_url"] = "sogoumobilebrowser";
                        $insertParam["source_device_type"] = $deviceType;
                        return BlackAccessLog::create($insertParam);
                    }

                    // 安卓手机单独处理
                    if ($deviceType == "android") {
                        // oppo手机浏览器
                        if (strpos($userAgent, "oppobrowser") !== false) {
                            // uc浏览器拦截
                            $insertParam["source_type"] = "browser";
                            $insertParam["from_url"] = "oppobrowser";
                            $insertParam["source_device_type"] = $deviceType;
                            return BlackAccessLog::create($insertParam);
                        }

                        // 欧朋
                        if (strpos($userAgent, "opr") !== false) {
                            $insertParam["source_type"] = "browser";
                            $insertParam["from_url"] = "opr";
                            return BlackAccessLog::create($insertParam);
                        }

                        // 小米
                        if (strpos($userAgent, "miuibrowser") !== false) {
                            $insertParam["source_type"] = "browser";
                            $insertParam["from_url"] = "miuibrowser";
                            $insertParam["source_device_type"] = $deviceType;
                            return BlackAccessLog::create($insertParam);
                        }

                        // 三星
                        if (strpos($userAgent, "samsungbrowser") !== false) {
                            $insertParam["source_type"] = "browser";
                            $insertParam["from_url"] = "samsungbrowser";
                            $insertParam["source_device_type"] = $deviceType;
                            return BlackAccessLog::create($insertParam);
                        }
                    }

                    // 苹果手机 单独处理的浏览器
                    if ($deviceType == "iphone") {
                        // Safari浏览器
                        if (strpos($userAgent, "version") !== false) {
                            // 苹果浏览器safari
                            $insertParam["source_type"] = "browser";
                            $insertParam["from_url"] = "safari";
                            $insertParam["source_device_type"] = $deviceType;
                            return BlackAccessLog::create($insertParam);
                        }
                    }

                    // 其他
                    if (strpos($userAgent, "browser") !== false) {
                        $insertParam["source_type"] = "browser";
                        $insertParam["from_url"] = "otherbrowser";
                        $insertParam["source_device_type"] = $deviceType;
                        return BlackAccessLog::create($insertParam);
                    }
                }
            }
        }

//        if ($source == 'mof') {
//            $insertParam["source_type"] = "weixin";
//            return BlackAccessLog::create($insertParam);
//        }


        if (empty($this->cookie['refresh_i'])) {
            //  TODO:  分享 只有当复制的链接是带source后缀的才会记录
            if (!empty($source) && $this->isBrowser($deviceType, $userAgent)) {
                // 判断处理
                if ($channelResult->share_flag == 0) {
                    $insertParam["source_type"] = "share";
                    return BlackAccessLog::create($insertParam);
                }
            }
        }

        return null;
    }


    /**
     * 判断是不是安卓或者苹果手机
     *
     * @param $agent
     *
     * @return string
     */
    private function isAndoridOrIphone($agent)
    {
        if (strpos($agent, 'iphone') !== false) {
            return "iphone";
        } else if (strpos($agent, 'android') !== false) {
            return "android";
        } else {
            return "";
        }
    }

    /**
     * 判断是不是安卓 返回boolean
     *
     *
     * @return string
     */
    private function isAndorid()
    {
        $agent = strtolower($this->useAgent);
        if (strpos($agent, 'android') !== false) {
            return true;
        }
        return false;
    }

    /**
     * 是不是浏览器
     *
     * @param        $deviceType
     * @param string $userAgent
     *
     * @return bool
     */
    private function isBrowser($deviceType, $userAgent = '')
    {
        $agent = new Agent();
        if ($agent->isTablet($userAgent) || $agent->isDesktop($userAgent)) {
            return true;
        }

        // uc 头部 安卓和苹果没啥区别
        if (strpos($userAgent, "ucbrowser") !== false ||
            strpos($userAgent, "ucweb") !== false
        ) {
            return true;
        }

        // 百度App 安卓和苹果没啥区别
        if (strpos($userAgent, "baiduboxapp") !== false) {
            return true;
        }

        // qq浏览器
        if (strpos($userAgent, "mqqbrowser") !== false) {
            return true;
        }

        // 百度浏览器
        if (strpos($userAgent, "baidubrowser") !== false) {
            return true;
        }

        // 搜狗浏览器
        if (strpos($userAgent, "sogoumobilebrowser") !== false) {
            return true;
        }

        // 安卓手机单独处理
        if ($deviceType == "android") {
            // oppo手机浏览器
            if (strpos($userAgent, "oppobrowser") !== false) {
                return true;
            }

            // 欧朋
            if (strpos($userAgent, "opr") !== false) {
                return true;
            }

            // 小米
            if (strpos($userAgent, "miuibrowser") !== false) {
                return true;
            }

            // 三星
            if (strpos($userAgent, "samsungbrowser") !== false) {
                return true;
            }
        }

        // 苹果手机 单独处理的浏览器
        if ($deviceType == "iphone") {
            // Safari浏览器
            if (strpos($userAgent, "version") !== false) {
                // 苹果浏览器safari
                return true;
            }
        }

        // 其他
        if (strpos($userAgent, "browser") !== false) {
            return true;
        }
        return false;
    }
}
